package com.github.thinwonton.showcase.groovy.introduce;

import org.apache.commons.io.IOUtils;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * JavaParseGroovy
 *
 * @author hugo
 * @date 2019/10/31
 */
public class JavaParseGroovy {
    static String groovyFile = "script.groovy_template";

    public static void main(String[] args) throws IOException, ScriptException {
        ScriptEngineManager engineManager = new ScriptEngineManager();
        ScriptEngine engine = engineManager.getEngineByName("groovy");
        //先测试下，行不行
        System.out.println("groovy解析结果:" + engine.eval("println 'HelloWord' \n 'HelloWordReturn'"));
        //读取源Groovy源程序
        String filePath = classPath() + groovyFile;
        String scriptContent = IOUtils.toString(new FileInputStream(filePath), StandardCharsets.UTF_8);
        System.out.println("----------groovy-exec----------");
        engine.eval(scriptContent);
    }

    public static String classPath() {
        return JavaParseGroovy.class.getClassLoader().getResource("").getPath();
    }
}
